//
//  UserDynamicViewController.m
//  RedGrass
//
//  Created by 徐良俊 on 2019/3/19.
//  Copyright © 2019 hongcaosp. All rights reserved.
//

#import "UserDynamicViewController.h"
#import "LoadMoreControl.h"
#import "GKDYVideoPlayer.h"
#import "RGMeDynamicsCell.h"
#import <AFNetworking/AFNetworking.h>
#import "RGMeInterfaceBulider.h"

#define  itemBaseTag  100000

@interface UserDynamicViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,GKDYVideoPlayerDelegate>
@property (nonatomic, strong) UICollectionView                 *collectionView;
@property (nonatomic, strong) LoadMoreControl                  *loadMore;
@property (nonatomic, assign) NSInteger                        pageIndex;
@property (nonatomic, assign) NSInteger                        pageSize;

@property (strong, nonatomic) GKDYVideoPlayer *vedioPlayer;
//@property (assign, nonatomic) NSInteger  itemIndex;

@property (strong, nonatomic) NSIndexPath *playingPath;

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic, copy) void(^listScrollViewScrollBlock)(UIScrollView *scrollView);

@property (nonatomic,assign) Boolean visible;
@end

@implementation UserDynamicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _dataArray = [NSMutableArray new];
    [self.view addSubview:self.collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    _loadMore = [[LoadMoreControl alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 50) surplusCount:15];
//    [_loadMore startLoading];
//    [self loadData:self.userId loadMore:NO];
    __weak __typeof(self) wself = self;
    [_loadMore setOnLoad:^{
        [wself loadData:wself.userId loadMore:YES];
    }];
    [_collectionView addSubview:_loadMore];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _visible = NO;
    if([_vedioPlayer isPlaying]){
        [_vedioPlayer pausePlay];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if([_dataArray count]){
        RGRecommendVideoModel *model = _dataArray[indexPath.row];
        return CGSizeMake(KScreenWidth, model.cellHeight);
    }
    return  CGSizeMake(KScreenWidth, 0);
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_dataArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RGMeDynamicsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RGMeDynamicsCell" forIndexPath:indexPath];
    cell.tag = itemBaseTag + indexPath.row;
    cell.vedioModel = [self.dataArray objectAtIndex:indexPath.row];
    AA_WEAK_MAKE(self)weakSelf = self;
    [cell setActionBtnClickBlock:^(NSInteger tag) {
        if(tag == kFocusListFocusTag){//点赞
            if([weakSelf.userViewDelegate respondsToSelector:@selector(favoriteVedioWithView: vedioModel:)]){
                [weakSelf.userViewDelegate favoriteVedioWithView:indexPath vedioModel:weakSelf.dataArray[indexPath.row]];
            }
        }else if (tag == kFocusListCommentTag){//评论
            if([weakSelf.userViewDelegate respondsToSelector:@selector(comementVedioWithView: vedioModel:)]){
                [weakSelf.userViewDelegate comementVedioWithView:indexPath vedioModel:weakSelf.dataArray[indexPath.row]];
            }
        }else if (tag == kFocusListShareTag){//g转发
            if([weakSelf.userViewDelegate respondsToSelector:@selector(shareVedioWithView: vedioModel:)]){
                [weakSelf.userViewDelegate shareVedioWithView:indexPath vedioModel:weakSelf.dataArray[indexPath.row]];
            }
        }else if (tag == kFocusListPlayBtnTag){//点击了播放按钮
            [weakSelf updateCellVedioPlayStatusWithIndexPath:indexPath];
            
        }else if (tag == kFocusListUserIconTag){//点击了图像
            
        }
    }];
    return cell;
    
}

-(void)onShow {
    _visible = YES;
    
}

-(void)onHide {
    _visible = NO;
    if(_vedioPlayer && [_vedioPlayer isPlaying]){
        [_vedioPlayer pausePlay];
    }
}

- (void)player:(GKDYVideoPlayer *)player statusChanged:(GKDYVideoPlayerStatus)status{
//    NSInteger index = _itemIndex - itemBaseTag;
//    if(index < 0){
//        return;
//    }
    if (!_playingPath) {
        return;
    }
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:_playingPath];
    if([cell isKindOfClass:[RGMeDynamicsCell class]]){
        if(_vedioPlayer.status == GKDYVideoPlayerStatusPlaying){
            cell.isShowPlayBtn = YES;
        } else if (_vedioPlayer.status == GKDYVideoPlayerStatusPaused){
            cell.isShowPlayBtn = NO;
        } else if (_vedioPlayer.status == GKDYVideoPlayerStatusLoading) {
            cell.loading = YES;
        }
    }
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
-(UICollectionView *)collectionView{
    if(!_collectionView){
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.minimumLineSpacing = 10;
//        flowLayout.estimatedItemSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width, 200);
        _collectionView = [[UICollectionView  alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            //            _collectionView.automaticallyAdjustsScrollViewInsets = NO;
        }
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[RGMeDynamicsCell class] forCellWithReuseIdentifier:@"RGMeDynamicsCell"];
        
    }
    return _collectionView;
}

-(GKDYVideoPlayer *)vedioPlayer{
    if(!_vedioPlayer){
        _vedioPlayer = [[GKDYVideoPlayer alloc]init];
        _vedioPlayer.delegate = self;
    }
    return _vedioPlayer;
}

-(void)refreshData {
    [self.loadMore reset];
    [self.loadMore startLoading];
    [self loadData:self.userId loadMore:NO];
}

- (void)loadData:(NSInteger)userId loadMore:(Boolean)loadMore {
    AA_WEAK_MAKE(self) weakSelf = self;
    if (loadMore) {
        _pageIndex++;
    } else {
        _pageIndex = 1;
    }
    HttpRequest *quest;
    quest = [HttpRequest buildRequest:url_userDynamic];
    NSDictionary *params = [RGMeInterfaceBulider buildUserDynamic:userId WithPageNumber:self.pageIndex pageSize:PageSize];
    [quest post:params success:^(id data) {
        weakSelf.pageIndex ++;
        
        NSArray *array = [RGRecommendVideoModel arrayOfModelsFromDictionaries:[data objectForKey:@"list"] error:nil];
        if (!loadMore) {
            weakSelf.dataArray = [NSMutableArray new];
            [weakSelf.dataArray addObjectsFromArray:array];
            [weakSelf.collectionView reloadData];
            if(weakSelf.pageIndex == 1){
                [weakSelf playVedioWithFirstIndexWhenLoadSuccess];
            }
        } else {
            [UIView setAnimationsEnabled:NO];
            [weakSelf.collectionView performBatchUpdates:^{
                [weakSelf.dataArray addObjectsFromArray:array];
                NSMutableArray<NSIndexPath *> *indexPaths = [NSMutableArray array];
                for(NSInteger row = weakSelf.dataArray.count - array.count; row<weakSelf.dataArray.count; row++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
                    [indexPaths addObject:indexPath];
                }
                [weakSelf.collectionView insertItemsAtIndexPaths:indexPaths];
            }completion:^(BOOL finished) {
                [UIView setAnimationsEnabled:YES];
                if(weakSelf.pageIndex == 1){
                    [weakSelf playVedioWithFirstIndexWhenLoadSuccess];
                }
            }];
        }
        
        [weakSelf.loadMore endLoading];
        if(array.count < PageSize) {
            [weakSelf.loadMore loadingAll];
        }
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf.loadMore loadingFailed];
    }];
}

//更新当前cell的视频播放状态
-(void) updateCellVedioPlayStatusWithIndexPath:(NSIndexPath *)path{
    if(![path isEqual:_playingPath]){//点击的不是当前的播放视频的cell
        [self playVideo:path];
        return;
    }
    if(_vedioPlayer.status == GKDYVideoPlayerStatusPlaying){
        [_vedioPlayer pausePlay];
        
    }else if (_vedioPlayer.status == GKDYVideoPlayerStatusPaused){
        [_vedioPlayer resumePlay];
    }
}

-(void)playVideo:(NSIndexPath *)path {
    if (_playingPath) {
        RGMeDynamicsCell *oldCell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:path];
        oldCell.isShowPlayBtn = NO;
    }
    _playingPath = path;
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:path];
//    self.itemIndex = cell.tag;
    [self.vedioPlayer removeVideo];
    [self.vedioPlayer playVideoWithView:cell.vedioGroudView url:cell.vedioUrl];
    if([self.userViewDelegate respondsToSelector:@selector(updateVedioPlayCountWithVedioId:)]){
        [self.userViewDelegate updateVedioPlayCountWithVedioId:cell.vedioModel.ID];
    }
}

-(void) playVedioWithFirstIndexWhenLoadSuccess{
    if (_visible) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self playVideo:[NSIndexPath indexPathForRow:0 inSection:0]];
        });
    }
//    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
////    self.itemIndex = cell.tag;
//    [self.vedioPlayer removeVideo];
//    [self.vedioPlayer playVideoWithView:cell.vedioGroudView url:cell.vedioUrl];
//    if([self.userViewDelegate respondsToSelector:@selector(updateVedioPlayCountWithVedioId:)]){
//        [self.userViewDelegate updateVedioPlayCountWithVedioId:cell.vedioModel.ID];
//    }
}

-(void) startFavoriteAnimationWithIsFavorite:(BOOL)isFavorite cellIndex:(NSInteger)index{
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    if([cell isKindOfClass:[RGMeDynamicsCell class]] && cell != nil){
        [cell updateFaroviteStauts];
    }
}

-(void) updateCommentCountsWhenCommentSuccessWithCellIndex:(NSInteger)cellIndex{
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:cellIndex inSection:0]];
    if([cell isKindOfClass:[RGMeDynamicsCell class]] && cell != nil){
        [cell updateCommentCounts];
    }
}
//转发成功后更新转发数
-(void)updateforwardCountsWhenShareSuccessWithCellIndex:(NSInteger)cellIndex{
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:cellIndex inSection:0]];
    if([cell isKindOfClass:[RGMeDynamicsCell class]] && cell != nil){
        [cell updateForwardCounts];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    !self.listScrollViewScrollBlock ? : self.listScrollViewScrollBlock(scrollView);
    [self _scrollViewScrolling];
}

#pragma mark - GKPageListViewDelegate
- (UIScrollView *)listScrollView {
    return self.collectionView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView * _Nonnull))callback {
    self.listScrollViewScrollBlock = callback;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    /*
     如果用户一旦接触scrollview就返回YES,有可能还没有开始拖动
     @property(nonatomic,readonly,getter=isTracking)     BOOL tracking;
     如果用户已经开始拖动就返回YES，
     @property(nonatomic,readonly,getter=isDragging)     BOOL dragging;
     如果用户没有在拖动（手指没有接触scrollview）就返回YES，但是scrollview仍然在惯性滑动
     @property(nonatomic,readonly,getter=isDecelerating) BOOL decelerating;
     */
    BOOL scrollToScrollStop = !self.collectionView.isTracking && !self.collectionView.isDragging && !self.collectionView.isDecelerating;
    if (scrollToScrollStop) {
        [self _scrollViewDidStopScroll];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    if (!decelerate) {
        BOOL dragToDragStop = !self.collectionView.isTracking && !self.collectionView.isDragging && !self.collectionView.isDecelerating;
        if (dragToDragStop) {
            [self _scrollViewDidStopScroll];
        }
    }
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    
    [self _scrollViewDidStopScroll];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    [self _scrollViewBeginDragging];
}


#pragma mark - helper

- (void)_scrollViewDidStopScroll {
    NSLog(@"tableview已经停止滚动");
    CGPoint pInView = [self.view convertPoint:self.collectionView.center toView:self.collectionView];
    NSIndexPath *path = [_collectionView indexPathForItemAtPoint:pInView];
//    RGMeDynamicsCell  *cell = (RGMeDynamicsCell *)[_collectionView cellForItemAtIndexPath:path];
//    if (cell) {
        if([path isEqual:_playingPath]){//表示是当前
            
        } else {
//            _itemIndex = cell.tag;
            [self playVideo:path];
//            [_vedioPlayer removeVideo];
//            [self.vedioPlayer playVideoWithView:cell.vedioGroudView url:cell.vedioUrl];
//            if([self.userViewDelegate respondsToSelector:@selector(updateVedioPlayCountWithVedioId:)]){
//                [self.userViewDelegate updateVedioPlayCountWithVedioId:cell.tag-itemBaseTag];
//            }
        }
//    }
    
}

- (void)_scrollViewBeginDragging {
//    self.zf_lastOffsetY = self.collectionView.contentOffset.y;
}


- (void)_scrollViewScrolling {
    NSArray<NSIndexPath *> *visiblePaths = [self.collectionView indexPathsForVisibleItems];
    if (visiblePaths.count > 0) {
        for (NSIndexPath *path in visiblePaths) {
            if ([path isEqual:_playingPath]) {
                return;
            }
        }
    }
    if ([_vedioPlayer isPlaying]) {
        [_vedioPlayer removeVideo];
    }
}

@end
